#!/bin/bash
BUILDDIR=build-win$PT_BIT

if [ "$PT_REPO_PATH" = "" ]; then echo "PT_REPO_PATH not set!" ; exit 1 ; fi
if [ "$PT_BINDIR" = "" ];    then echo "PT_BINDIR not set!" ; exit 1 ; fi
if [ "$PT_BIT" = "" ];       then echo "PT_BIT not set!" ; exit 1 ; fi

if [ ! -d "$PT_REPO_PATH" ]; then
  echo "Path to repository \"$PT_REPO_PATH\" not found."
  exit
fi


if [ "$1" = "all" ]; then
  ACTIONMSG="Complete re-build of Photivo ${PT_BIT}bit"
  UPDATEMSG=""
  QMAKECLI="qmake ../photivo.pro CONFIG+=WithoutGimp CONFIG-=debug"
elif [ "$1" = "q" ]; then
  ACTIONMSG="Updating Photivo ${PT_BIT}bit"
  UPDATEMSG="\n Rebuilding makefiles"
  QMAKECLI="qmake ../photivo.pro CONFIG+=console CONFIG+=WithoutGimp CONFIG+=WithoutClear CONFIG-=debug"
elif [ "$1" = "" ]; then
  ACTIONMSG="Updating Photivo ${PT_BIT}bit"
  UPDATEMSG=""
  QMAKECLI=""
else
  echo "Unrecognized mode: \"$1\"."
  echo ""
  echo "Usage: photivo-build [all|q]"
  echo "This script never builds the Gimp plugin, Adobe profiler or Curves creator."
  echo "all"
  echo "  Full build: First removes all makefiles and object files. Then runs"
  echo "  qmake (console disabled, ptClear enabled) and make. Afterwards copies "
  echo "  the binaries to $PT_BINDIR and updates the subfolders there."
  echo "  DLLs are not updated. Use photivo-update-libs for that."
  echo "[no option]"
  echo "  Update build: Runs make and copies photivo.exe to $PT_BINDIR."
  echo "q"
  echo "  Update build: Runs qmake to enable the console and disable ptClear."
  echo "  then runs make and copies photivo.exe to $PT_BINDIR."
  exit
fi


echo "------------------------------------"
echo " $ACTIONMSG"
echo -e " $PT_REPO_PATH$UPDATEMSG"
echo "------------------------------------"
echo 

cd "$PT_REPO_PATH"
if [ -d "$BUILDDIR" ]; then
  if [ "$1" = "all" ]; then
    echo "Cleaning ..."
    cd "$BUILDDIR" && rm -rf *
  else
    cd "$BUILDDIR"
    if [ "$1" = "q" ]; then
      rm -f Makefile* photivoProject/Makefile* Objects/ptMain.o
    fi
  fi
else
  mkdir "$BUILDDIR"
  cd "$BUILDDIR"
fi

echo "Building ..."
echo
$QMAKECLI
make -j4


if [ -s ./photivo.exe ]; then
  if [ ! -d "../$PT_BINDIR" ]; then
    mkdir "../$PT_BINDIR"
    echo "$PT_BINDIR did not exist!"
    echo "You might want to run photivo-update-libs."
  fi

  cd "../$PT_BINDIR"
  
  if [ "$1" = "all" ]; then
    photivo-update-datafiles
    cp ../${BUILDDIR}/ptClear.exe .
  else
    echo "Copying photivo.exe ..."
  fi
  
  cp ../${BUILDDIR}/photivo.exe .
  echo "Finished."
fi
